{% extends 'base.html' %}
{% load i18n %}

{% block content %}
    <section class="container new-premise">
        <form action="?view={{ view }}" method="post">
            {% if parent %}
                <div class="parent-premise">
                    <strong>{% trans "The parent premise:" %}</strong>
                    <p>{{ parent.text }}</p>
                </div>
            {% endif %}
            {% csrf_token %}
            {{ form.as_p }}
            <input type="submit" value="{% trans "Submit" %}" class="submit">
        </form>
    </section>
{% endblock %}

{% block extra-scripts %}
    <script type="text/javascript">
    $(function () {
        var relatedArgumentLabel = "{{ premise.related_argument.title }}";

        var textarea = $("#id_text"),
            container = $("<div>", {
                "class": "remained-char"
            }).appendTo(textarea.parent())
              .html("{% trans "Characters remaining: " %}"),
            remained = $("<span>").appendTo(container);
        var update = function (event) {
            var max = parseInt(textarea.attr("maxlength")),
                _remained = max - textarea.val().length;
            remained.html(_remained);
        };
        textarea.keyup(update);
        update();

        var relatedArgument = $('#id_related_argument');

        var selectArgument = function (label) {
            var selectedArgument = $("<div />", {
                'class': 'selected-argument'
            }).html(
                label
            ).append(
                $("<a />")
                 .html(
                    '{% trans "(change)" %}'
                 ).on('click', function (event) {
                    event.preventDefault();
                    relatedArgument.val("").show();
                    selectedArgument.remove();
                 }.bind(this))
            );
            relatedArgument.hide().after(selectedArgument);
        };

        relatedArgument.autocomplete({
            source: function(search, callback) {
                $.getJSON("{% url "contentions_search" %}", {
                    keywords: search.term,
                    json: true
                }, callback);
            },
            select: function(event, ui) {
                $(this).val(ui.item.id);
                selectArgument(ui.item.label);
                return false;
            }
        });

        if (relatedArgument.val()) {
            selectArgument(relatedArgumentLabel);
        }
    });
    </script>
{% endblock %}